(function(global){
	if(!String.prototype.format){
		String.prototype.format = function() {
			var args = Array.prototype.slice.call(arguments);
			return this.replace(/\{(\d+)\}/g, 
				function(m, i){
					return args[i];
				});
		};
	}

	var Yo = {
		log: {}
	};

	Yo.host = global.host != null ? global.host : (function(){
		var host = 'http://tech11.cn';
		if(document.location.host == 'localhost')
			host = 'http://localhost';

		return host;
	})();

	// log api
	Yo.log.i = function(obj){
		console.log(obj);
	};

	// log api
	Yo.log.debug = function(obj){
		console.log(obj);
		if(Yo.isDebug)
			alert(obj);
	};

	// selector shortcut
	Yo.role = function(name){
		return $('[data-role="' + name + '"]');
	};

	global.Yo = Yo;
})(this);

(function(Yo){
	// easytemplate
	var easyTemplate = function(s, d) {
		if (!s) {
			return '';
		}
		if (s !== easyTemplate.template) {
			easyTemplate.template = s;
			easyTemplate.aStatement = easyTemplate
					.parsing(easyTemplate.separate(s));
		}
		var aST = easyTemplate.aStatement;
		var process = function(d2) {
			if (d2) {
				d = d2;
			}
			return arguments.callee;
		};
		process.toString = function() {
			return (new Function(aST[0], aST[1]))(d);
		};
		return process;
	};
	easyTemplate.separate = function(s) {
		var r = /\\'/g;
		var sRet = s.replace(
				/(<(\/?)#(.*?(?:\(.*?\))*)>)|(')|([\r\n\t])|(\$\{([^\}]*?)\})/g,
				function(a, b, c, d, e, f, g, h) {
					if (b) {
						return '{|}' + (c ? '-' : '+') + d + '{|}';
					}
					if (e) {
						return '\\\'';
					}
					if (f) {
						return '';
					}
					if (g) {
						return '\'+(' + h.replace(r, '\'') + ' || \'\')+\'';
					}
				});
		return sRet;
	};
	easyTemplate.parsing = function(s) {
		var mName, vName, sTmp, aTmp, sFL, sEl, aList, aStm = [ 'var aRet = [];' ];
		aList = s.split(/\{\|\}/);
		var r = /\s/;
		while (aList.length) {
			sTmp = aList.shift();
			if (!sTmp) {
				continue;
			}
			sFL = sTmp.charAt(0);
			if (sFL !== '+' && sFL !== '-') {
				sTmp = '\'' + sTmp + '\'';
				aStm.push('aRet.push(' + sTmp + ');');
				continue;
			}
			aTmp = sTmp.split(r);
			switch (aTmp[0]) {
			case '+macro':
				mName = aTmp[1];
				vName = aTmp[2];
	//			aStm.push('aRet.push("<!--' + mName + ' start--\>");');
				break;
			case '-macro':
	//			aStm.push('aRet.push("<!--' + mName + ' end--\>");');
				break;
			case '+if':
				aTmp.splice(0, 1);
				aStm.push('if' + aTmp.join(' ') + '{');
				break;
			case '+elseif':
				aTmp.splice(0, 1);
				aStm.push('}else if' + aTmp.join(' ') + '{');
				break;
			case '-if':
				aStm.push('}');
				break;
			case '+else':
				aStm.push('}else{');
				break;
			case '+list':
				aStm.push('if(' + aTmp[1] + '.constructor === Array){with({i:0,l:'
						+ aTmp[1] + '.length,' + aTmp[3] + '_index:0,' + aTmp[3]
						+ ':null}){for(i=l;i--;){' + aTmp[3] + '_index=(l-i-1);'
						+ aTmp[3] + '=' + aTmp[1] + '[' + aTmp[3] + '_index];' 
						+ 'if(!' + aTmp[3] + '){break;}');
				break;
			case '-list':
				aStm.push('}}}');
				break;
			default:
				break;
			}
		}
		aStm.push('return aRet.join("");');
		if (!vName) {
			aStm.unshift('var data = arguments[0];');
		}
		return [ vName, aStm.join('') ];
	};

	Yo.format = function(txt, data){
		return easyTemplate(txt, data).toString();
	};
})(this.Yo);

(function(Yo){
	// localstorage
	var Storage = function(){
		this.storage = window.localStorage;
		if(!this.storage)
			Yo.log.i('Web local storage api not support!');
	};

	var extend = {
		clear: function(){
			if(!this.storage)
				return;

			this.storage.clear();
		}, 

		get: function(key){
			if(!this.storage)
				return;

			var str = this.storage[key];
			if(!str || 'undefined' == str || 'null' == str)
				return null;

			return JSON.parse(str);
		}, 

		set: function(key, val){
			if(!this.storage)
				return;

			this.storage[key] = JSON.stringify(val);
		},
			
		remove: function(key){
			if(!this.storage)
				return;

			this.storage.removeItem(key);
		}
	};

	for(key in extend){
		Storage.prototype[key] = extend[key];
	}
	Yo.Storage = Storage;
})(this.Yo);

(function(Yo){
	var Utils = {};

	// cookie helper
	Utils.getCookie = function(cookieName){
		var cookieStart = document.cookie.indexOf(cookieName);
		var cookieEnd = document.cookie.indexOf(";", cookieStart);
		return cookieStart == -1 ? '' : unescape(document.cookie.substring(cookieStart + cookieName.length + 1, (cookieEnd > cookieStart ? cookieEnd : document.cookie.length)));
	};

	Utils.setCookie = function(cookieName, cookieValue, seconds, path, domain, secure) {
		var expires = new Date();
		expires.setTime(expires.getTime() + seconds);
		document.cookie = escape(cookieName) + '=' + escape(cookieValue)
			+ (expires ? '; expires=' + expires.toGMTString() : '')
			+ (path ? '; path=' + path : '/')
			+ (domain ? '; domain=' + domain : '')
			+ (secure ? '; secure' : '');
	};

	// id:1;name:xxx -> {id: 1, name: xxx}
	Utils.str2params = function(str){
		var params = {};
		if(!str)
			return params;

		_.each(str.split(';'), function(it){
			var arr = it.split(':');
			params[arr[0]] = arr[1];
		});

		return params;
	};

	// query parameters
	Utils.params = function(url){
		url = url || document.location.href;
		var data = {};
		var pos = url.indexOf('?');
		if(pos != -1){
			var query = url.substring(pos);
			if(query){
				var ll = query.substring(1).split('&');
				var i = 0;
				for(; i < ll.length; i++){
					var arr = ll[i].split('=');
					if(arr.length == 2)
						data[arr[0]] = decodeURI(arr[1]);
				}
			}
		}
		return data;
	};

	Utils.alert = function(msg){
		alert(msg);
	};

	Utils.confirm = function(msg){
		confirm(msg);
	};

	Yo.Utils = Utils;
})(this.Yo);

(function(Yo){
	// pagination
	var Pager = function(pageNum, pageSize, totalCount){
		this.pageNum = pageNum;
		this.pageSize = pageSize;
		this.totalCount = totalCount;

		this.ll = [];
		this.cb = function(){};
	};

	Pager.prototype.init = function(preBtnId, nextBtnId, cb){
		this.preBtnId = preBtnId;
		this.nextBtnId = nextBtnId;
		this.cb = cb;
		
		var that = this;
		$('#' + preBtnId).click(function(e){
			e.preventDefault();

			that.pageNum--;
			that.render();
		});

		$('#' + nextBtnId).click(function(e){
			e.preventDefault();

			that.pageNum++;
			that.render();
		});		
	};
	Pager.prototype.setList = function(ll){
		if(ll){
			this.ll = ll;
			this.totalCount = ll.length;
		}else{
			this.ll = [];
			this.totalCount = 0;
		}
	};
	Pager.prototype.getStart = function(){
		return (this.pageNum - 1) * this.pageSize;
	};
	Pager.prototype.getEnd = function(){
		return this.pageNum * this.pageSize;
	};
	Pager.prototype.hasPre = function(){
		return this.pageNum > 1;
	};
	Pager.prototype.hasNext = function(){
		return this.pageNum * this.pageSize < this.totalCount;
	};
	Pager.prototype.getTotalPageNum = function(){
		var num = Math.floor(this.totalCount / this.pageSize);
		if(this.totalCount % this.pageSize != 0)
			num++;

		return num;
	};

	Pager.prototype.render = function(){
		var subList = this.ll.slice(this.getStart(), this.getEnd());
		this.cb(subList);

		$('#' + this.preBtnId)[this.hasPre() ? 'show' : 'hide']();
		$('#' + this.nextBtnId)[this.hasNext() ? 'show' : 'hide']();
	};

	Yo.Pager = Pager;
})(this.Yo);

(function(Yo){
	var Storage = Yo.Storage;

	var Conf = {};
	Conf.get = function(key){
		var storage = new Storage();
		return storage.get(key);
	};
	Conf.set = function(key, val){
		var storage = new Storage();
		storage.set(key, val);
	};
	Conf.remove = function(key){
		var storage = new Storage();
		storage.remove(key);
	};
	Yo.Conf = Conf;
})(this.Yo);

(function(Yo){
	var Utils = Yo.Utils;
	var Conf = Yo.Conf;

	var User = {
		KEY: 'userLogin',
		COOKIE_KEY: 'yo-user-login'
	};
	User.getFromCookie = function(){
		var str = Utils.getCookie(this.COOKIE_KEY);
		if(!str)
			return null;

		return JSON.parse(JSON.parse(str));
	};
	User.get = function(){
		return Conf.get(this.KEY);
	};
	User.set = function(val){
		Conf.set(this.KEY, val);
	};
	User.remove = function(){
		Utils.setCookie(this.COOKIE_KEY, '');
		Conf.remove(this.KEY);
	};
	Yo.User = User;
})(this.Yo);

(function(Yo){
	// modals
	var Section = {
		handlers: {},
		interceptors: [],

		// load once
		flags: {}, 

		// for window.history
		his: {
			ll: []
		}, 

		addInter: function(pat, fn){
			this.interceptors.push({pat: pat, fn: fn});
		}, 

		addPageFn: function(page, fn, onlyOnce){
			this.handlers[page] = onlyOnce ? (function(key){
				return function(){
					if(!Section.flags[key]){
						fn();
						Section.flags[key] = true;
					}
				};
			})(page + '_loadOnce') : fn;
		}
	};
	Section.show = function(page){
		var modal = $('#' + page);
		modal.addClass('active');

		this.his.push('#' + page);
	};
	Section.hide = function(page){
		var modal = $('#' + page);
		modal.removeClass('active');

		this.his.remove('#' + page);
	};

	Section.go = function(page, force, params){
		if(!force){
			var i = 0;
			for(; i < this.interceptors.length; i++){
				var it = this.interceptors[i];
				if(typeof it.pat == 'object' && it.pat.constructor == RegExp){
					if(page.match(it.pat)){
						var isOk = it.fn(page);
						if(!isOk)
							return;
					}
				}
			}
		}

		this.show(page);
		var fn = this.handlers[page];
		if(fn)
			fn(params);
	};

	Section.his.getPageLast = function(){
		var pathname = document.location.pathname;
		var arr = pathname.split(/\//);
		var pathlast = arr[arr.length - 1];		

		return pathlast;
	};

	Section.his.backTo = function(page){
		var len = this.ll.length;
		var i = len - 1, one;
		for(; i >= 0; i--){
			one = this.ll[i];
			if(one.page == page){
				if('' == page){
				}else{
					var modal = $(page);
					if(!modal.hasClass('active'))
						modal.addClass('active');
				}
				one.status = '';
				break;
			}

			one.status = 'back';
			if('' == one.page){
			}else{
				var modal = $(one.page);
				if(modal.hasClass('active'))
					modal.removeClass('active');
			}
		}
	};

	Section.his.push = function(page){
		this.ll.push({page: page});

		// remove forward
		var len = this.ll.length;
		var i = len - 1, one, removedNumber = 0;
		for(; i > 0; i--){
			one = this.ll[i];
			if(one.status == 'back')
				removedNumber++;
			else
				break;
		}

		if(removedNumber){
			this.ll.slice(len - removedNumber, removedNumber);
		}

		var pathlast = this.getPageLast();
		history.pushState({page: page, type: 'modal'}, '', pathlast + page);
	};

	Section.his.last = function(){
		var len = this.ll.length;
		if(!len)
			return {page: ''};

		return this.ll[len - 1];
	};

	Section.his.remove = function(page){
		if(page != this.last().page){
			Yo.log.i('not last visited - ' + page);
			return;
		}

		this.ll.pop();
		var lastPage = this.last();

		var pathlast = this.getPageLast();
		history.replaceState({page: lastPage.page, type: 'modal'}, '', pathlast + lastPage.page);
	};

	Yo.Section = Section;
})(this.Yo);

(function(Yo){
	// http wrapper
	User = Yo.User;
	Section = Yo.Section;

	var Req = {};
	Req.get = function(url, params, cb){
		if(typeof params == 'function'){
			cb = params;
			params = {};
		}

		Pace.track(function(){
			$.get(Yo.host + url, params, function(data){
				if(data && data.error){
					if('session-invalid' == data.error){
						User.remove();
						Section.show('user-login');
						return;
					}else{
						alert(data.error);
					}
				}else{
					cb(data);
				}
			});
		});
	};
	Req.post = function(url, data, cb){
		Pace.track(function(){
			$.ajax({
				type: 'POST', 
				url: Yo.host + url, 
				data: JSON.stringify(data), 
				dataType: 'json', 
				contentType: 'application/json',
				success: function(data){
					if(data && data.error){
						if('session-invalid' == data.error){
							User.remove();
							Section.show('user-login');
							return;
						}else{
							alert(data.error);
						}
					}else{
						cb(data);
					}
				}, 
				error: function(xhr, errorType, error){
					console.error(error);
				}
			});
		});
	};

	Yo.Req = Req;
})(this.Yo);
(function(global){
	var Section = Yo.Section;
	var User = Yo.User;
	var Utils = Yo.Utils;

	var YoPages = {
		initPages: []
	};

	YoPages.initPages.push(function(){
		FastClick.attach(document.body);
		
		// modals
		$(document).on('click', 'a', function(e){
			var link = $(e.target);
			if(!link.is('a'))
				link = link.closest('a');

			var pageDyn = link.attr('yo-href');
			var pageStatic = link.attr('href');

			if(pageDyn){
				if(pageDyn.indexOf('#') == 0)
					pageDyn = pageDyn.substr(1);

				var paramsStr = link.attr('data-params');
				var params = Utils.str2params(paramsStr);

				Section.go(pageDyn, false, params);
			}else if(pageStatic){
				if(pageStatic.indexOf('#') == 0){
					// modal toggle, do not use touchend
					var modal = $(pageStatic);

					var isActive = modal.hasClass('active');
					modal.toggleClass('active');

					if(isActive){
						// close modal
						Section.his.remove(pageStatic);
					}else{
						Section.his.push(pageStatic);
					}
				}else{
					document.location.href = pageStatic;
				}
			}

			return false;
		});

		// history
		var isExist = 0;
		window.onpopstate = function(){
			var json = history.state;
			Yo.log.i(json);

			if(!json || !json.page){
				Section.his.backTo('');

				if(isExist > 1){
					if(navigator.app.exitApp)
						navigator.app.exitApp();
					else
						window.close();
				}else{
					isExist++;

					if(isExist > 1){
						var flag = Utils.confirm('确定要退出么？');
						if(flag)
							window.close();
					}
				}
			}else{
				Section.his.backTo(json.page);
				isExist = 0;
			}
		};

		// show default page
		var params = Utils.params();
		if(params.defaultPage){
			Section.go(params.defaultPage);
		}
	});

	YoPages.init = function(){
		var i = 0;
		for(; i < YoPages.initPages.length; i++){
			YoPages.initPages[i].call(YoPages);
		}
	};

	global.YoPages = YoPages;
})(this);
(function(global){
	var Peizi = function(type, amount, num, numMulti, dd){
		// 利率
		this.intPerDayEveryWan = 12;
		this.intPerMonthPercent = 0.013;

		this.type = type;
		this.typeStr = type == 'month' ? '月' : '天';

		this.amount = amount;
		this.num = num;
		this.numMulti = numMulti;

		// 创建时间
		dd = dd ? moment(dd) : moment();
		this.dayCreated = dd.format('YYYY-MM-DD');

		var dayBegin = dd.add(1, 'day');
		while(dayBegin.day() == 6 || dayBegin.day() == 0){
			dayBegin.add(1, 'day');
		}

		this.dayBegin = dayBegin.format('YYYY-MM-DD');
	};

	Peizi.prototype.cal = function(){
		this.amountTotal = this.amount * (this.numMulti + 1);

		this.amountWarning = Math.floor(this.amountTotal * 0.65)
		this.amountFlush = Math.floor(this.amountTotal * 0.52);

		this.intPerMonth = Math.ceil(this.numMulti * this.amount * this.intPerMonthPercent) || 1;
		this.amountInt = this.intPerMonth * this.num;

		this.amountIntStr = '{0}元/月 * {1}月 = 合计{2}'.format(this.intPerMonth, this.num, this.amountInt);

		if('day' == this.type){
			// 1万1天11块，2万1天22...
			var wanNum = Math.ceil(this.numMulti * this.amount / 10000) || 1;
			this.intPerDay = wanNum * this.intPerDayEveryWan;
			this.amountInt = this.intPerDay * this.num;
			this.amountIntStr = '{0}元/天 * {1}天 = 合计{2}'.format(this.intPerDay, this.num, this.amountInt);
		}
	};
	
	global.Peizi = Peizi;
})(this);

(function(global, Yo, YoPages){
	var Section = Yo.Section;
	var User = Yo.User;
	var Utils = Yo.Utils;
	var Req = Yo.Req;

	var Peizi = global.Peizi;

	var authUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
	var redirectUrl = 'http://tech11.cn/wx/ind/peizi/index?showwxpaytitle=1';
	Section.authUrl = authUrl.format('wx9f7507a78aa0c8f0', encodeURIComponent(redirectUrl));

	function showUser(user){
		$('#userNickname').text(user.nickname);
		$('#userHeaderImg').attr('src', user.headimgurl);
	}

	// main page
	YoPages.initPages.push(function(){
		User.remove();

		// user
		var user = global.userSaved;
		if(user){
			User.set(user);
			showUser(user);
		}else{
			User.remove();
			document.location.href = Section.authUrl;
		}

		var lastCal = {};
		// 金额、利息计算
		var cal = function(type){
			if(!type){
				var typeChoose = $('#pz-type .control-item');
				type = typeChoose.index(typeChoose.filter('.active')) == 0 ? 'month' : 'day';
			}

			var amount = $('#amount').val();
			if(!amount){
				lastCal = {};
				return;
			}
			amount = parseInt(amount);

			// 默认一天、月
			var num = $('#num').val();
			if(!num)
				num = '1';
			num = parseInt(num);

			// 默认配资一倍
			var numMulti = $('#numMulti').val();
			if(!numMulti)
				numMulti = '1';
			numMulti = parseInt(numMulti);

			var pz = new Peizi(type, amount, num, numMulti);
			pz.cal();

			$('#pzDayRange').text('' + pz.num + pz.typeStr);
			$('#pzDayBegin').text(pz.dayBegin);

			$('#pzAmountTotal').text(pz.amountTotal);
			$('#pzAmountWarning').text(pz.amountWarning);
			$('#pzAmountFlush').text(pz.amountFlush);

			$('#pzAmountInt').text(pz.amountIntStr);
			$('#totalPayed').text(pz.amount + pz.amountInt);

			lastCal.amount = amount;
			lastCal.type = type;
			lastCal.num = num;
			lastCal.numMulti = numMulti;
		};

		$('#pz-type .control-item').click(function(e){
			var type = $(e.target).attr('data-type');
			cal(type);
		});
		$('#amount,#num,#numMulti').change(function(e){
			var type = $(e.target).attr('data-type');
			cal();
		});

		// pay
		$('#btn-pay').click(function(){
			cal();

			if(!lastCal.amount){
				alert('请先输入本金和时间长度！');
				return;
			}

			if(lastCal.amount < 100){
				alert('本金金额不能小于100！');
				return;
			}

			var user = User.get();
			lastCal.openid = user.openid;

			Req.post('/wx/ind/peizi/apply', lastCal, function(data){
				if(data.flag){
					Yo.log.debug(data);
					wx.chooseWXPay({
						timestamp: data.timeStamp, 
						nonceStr: data.nonceStr, 
						package: data.package, 
						signType: data.signType, 
						paySign: data.paySign, 
						success: function (res) {
							Section.go('apply-list');
						}
					});
				}else{
					if(data.msg){
						alert(data.msg);
						return;
					}

					if('amount-required' == data.tips){
						alert('参数错误！');
					}else if('amount-rangeout' == data.tips){
						alert('本金必须在0-50000之间！');
					}else if('multi-rangeout' == data.tips){
						alert('配资倍数必须在1-5之间！');
					}else if('num-rangeout' == data.tips){
						alert('配资时间必须在1-50之间（最多50天或50个月）！');
					}else if('person-info' == data.tips){
						Section.go('person-info');
						alert('请先完善个人信息！');
					}else if('wx-order-failed' == data.tips){
						alert('创建微信支付订单失败，请联系客服人员！');
					}
				}
			});
		});

	});

	// person user info
	YoPages.initPages.push(function(){
		Section.addPageFn('person-info', function(){
			var user = User.get();
			var openid = user.openid;

			Req.get('/wx/ind/peizi/get-user-info', {openid: openid}, function(data){
				if(!data.flag){
					alert(data.msg);
					return;
				}

				var user = data.user;
				if(!user)
					return;

				$('#userId').text(user.idcardNo || '--');
				$('#userName').text(user.name || '--');
				$('#userTel').text(user.tel || '--');

				var preDir = '/wx/ind/peizi/img-show?serverId=';
				if(user.idcardPic){
					$('#userIdPic').attr('src', preDir + user.idcardPic);
				}
				if(user.idcardPic2){
					$('#userIdPic2').attr('src', preDir + user.idcardPic2);
				}
			});
		});

		// *** 个人信息身份证图片上传
		$('#btn-choose-idcard-pic,#btn-choose-idcard-pic2').click(function(){
			var user = User.get();
			var openid = user.openid;

			var isPic2 = $(this).attr('id').indexOf('pic2') != -1;
			wx.chooseImage({
				success: function(res){
					var localIds = res.localIds;
					if(!localIds.length)
						return;

					var localId = localIds[0];

					wx.uploadImage({
							localId: localId, 
							isShowProgressTips: 1, 
							success: function(res){
								var serverId = res.serverId;
								Yo.log.i('upload image result - ' + serverId);

								var preDir = '/wx/ind/peizi/img-show?serverId=';
								if(isPic2){
									$('#userIdPic2').attr('src', preDir + serverId);
								}else{
									$('#userIdPic').attr('src', preDir + serverId);
								}

								var params = {openid: openid, serverId: serverId};
								params.type = 'userId';
								params.isPic2 = isPic2;

								Req.post('/wx/ind/peizi/update-user-info', params, function(data){
								});
							}
					});
				}
			});			
		});

		// *** 个人信息修改按钮事件
		Yo.role('change-user-info').click(function(){
			$('#person-info form').hide();

			var field = $(this).attr('data-field');
			$('#form-' + field).show();

			var val = $(this).siblings('dd').text();
			if(val && val != '--')
				$('#input-' + field).val(val);

			$('#input-' + field).focus();
			$('#person-info .content')[0].scrollTop = 200;
		});

		// *** 修改身份证号码
		$('#btn-confirm-user-id').click(function(){
			var userId = $('#input-user-id').val();
			var isOk = /(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(userId.toUpperCase());
			if(!isOk){
				alert('请输入正确的身份证号码！');
				return;
			}

			var user = User.get();
			var openid = user.openid;

			var params = {};
			params.type = 'idcardNo';
			params.openid = openid;
			params.idcardNo = userId;

			Req.post('/wx/ind/peizi/update-user-info', params, function(data){
				if(data.flag){
					$('#userId').text(userId);
					$('#form-user-id').hide();
				}else{
					alert(data.msg);
				}
			});
		});

		// *** 修改真实姓名
		$('#btn-confirm-user-name').click(function(){
			var userName = $('#input-user-name').val();
			var isOk = userName.length >= 2;
			if(!isOk){
				alert('请输入您的真实姓名！');
				return;
			}

			var user = User.get();
			var openid = user.openid;

			var params = {};
			params.type = 'userName';
			params.openid = openid;
			params.userName = userName;

			Req.post('/wx/ind/peizi/update-user-info', params, function(data){
				if(data.flag){
					$('#userName').text(userName);
					$('#form-user-name').hide();
				}else{
					alert(data.msg);
				}
			});
		});

		// *** 发送手机验证码
		$('#btn-send-verify-code').click(function(){
			var userTel = $('#input-user-tel').val();
			var isOk = /^\d{11}$/.test(userTel);
			if(!isOk){
				alert('请输入您的手机号码！');
				return;
			}

			var params = {};
			params.userTel = userTel;

			Req.get('/wx/ind/peizi/send-tel-verify-code', params, function(data){
				if(data.flag){
					// wait 30 seconds TODO
					var totalSeconds = 30;
					$('#btn-send-verify-code').attr('disabled', 'disabled').find('span').text('' + totalSeconds).show();
					Section.intervalSendVerifyCode = setInterval(function(){
						var sp = $('#btn-send-verify-code span');
						var txt = sp.text();
						if(!txt)
							return;

						var counted = parseInt(txt) - 1;

						if(counted == 0){
							sp.text('').hide();
							$('#btn-send-verify-code').removeAttr('disabled');

							clearInterval(Section.intervalSendVerifyCode);
						}else{
							sp.text(counted);
						}
					}, 1000);
				}else{
					alert(data.msg);
				}
			});
		});

		// *** 修改手机号
		$('#btn-confirm-user-tel').click(function(){
			var userTel = $('#input-user-tel').val();
			var userTelVerifyCode = $('#input-user-tel-verify-code').val();

			var isOk = /^\d{11}$/.test(userTel);
			if(!isOk){
				alert('请输入您的手机号码！');
				return;
			}

			isOk = /^\d{4}$/.test(userTelVerifyCode);
			if(!isOk){
				alert('请输入4为数字验证码！');
				return;
			}

			var user = User.get();
			var openid = user.openid;

			var params = {};
			params.type = 'userTel';
			params.openid = openid;
			params.userTel = userTel;
			params.userTelVerifyCode = userTelVerifyCode;

			Req.post('/wx/ind/peizi/update-user-info', params, function(data){
				if(data.flag){
					$('#userTel').text(userTel);
					$('#form-user-tel').hide();
				}else{
					if(data.msg){
						alert(data.msg);
					}else{
						if('verify-code-expired' == data.tips){
							alert('验证码不正确或已经失效，请重新获取！');

//							$('#btn-send-verify-code').removeAttr('disabled').find('span').text('').hide();
//							if(Section.intervalSendVerifyCode){
//								clearInterval(Section.intervalSendVerifyCode);
//							}
						}
					}
				}
			});
		});

	});

	// apply list
	YoPages.initPages.push(function(){
		Section.addPageFn('apply-list', function(){
			var user = User.get();
			var openid = user.openid;

			var statusLabels = {
				1: '未支付',
				10: '已经支付', 
				20: '审核中',
				30: '通过审核', 
				40: '已经配资'
			};

			Req.get('/wx/ind/peizi/get-apply-list', {openid: openid}, function(data){
				if(!data.ll)
					return;

				_.each(data.ll, function(it){
					var pz = new Peizi(it.type, it.amount, it.num, it.numMulti, it.dd);
					pz.cal();

					it.dayCreated = pz.dayCreated;
					it.dayBegin = pz.dayBegin;

					it.typeStr = pz.typeStr;

					it.amountTotal = pz.amountTotal;
					it.amountWarning = pz.amountWarning;
					it.amountFlush = pz.amountFlush;

					it.amountIntStr = pz.amountIntStr;

					it.statusLabel = statusLabels[it.status];
				});

				var tpl = $('#tplApplyItemList').html();
				var html = Yo.format(tpl, data);
				$('#apply-list-content').html(html);
			});
		});
	});

})(this, Yo, YoPages);

